<template>
  <a-row>
    <a-col :span="2">
      <a-button type="primary" size="small">新增</a-button>
    </a-col>
    <a-col :span="4">
      <a-popconfirm
        title="你确定要删除吗"
        ok-text="确定"
        cancel-text="取消"
        @confirm="onDeleteIds"
        @visibleChange="onVisibleChange"
        :visible="visible"
      >
        <a-button type="primary" size="small">删除选中</a-button>
      </a-popconfirm>
    </a-col>

    <a-col :span="6">
      <a-input placeholder="请输入姓名" v-model:value="dto.name"></a-input>
    </a-col>
    <a-col :span="8">
      <a-input placeholder="请输入邮箱" v-model:value="dto.email"></a-input>
    </a-col>

    <a-col :span="2">
      <a-button type="primary" size="small" @click="handleTableChange"
        >搜索</a-button
      >
    </a-col>
  </a-row>

  <hr />

  <a-table
    :dataSource="userList"
    :columns="columns"
    :rowKey="rowkey"
    :loading="loading"
    :pagination="pagination"
    @change="handleTableChange"
    :row-selection="{ selectedRowKeys: ids, onChange: onSelectchange }"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'name'">
        {{ record.name + (record.name.length >= 4 ? "大" : "小") }}
      </template>

      <template v-else-if="column.dataIndex === 'operator'">
        <a>修改</a>
        <a-divider type="vertical"></a-divider>
        <a-popconfirm
          title="你确定删除该数据吗"
          ok-text="确定"
          cancel-text="取消"
          @confirm="doDelete(record.id)"
        >
          <a>删除</a>
        </a-popconfirm>
      </template>
    </template>
  </a-table>
</template>

<script setup lang="ts">
import { ApiResponse, ApiCommonResponse, User } from "../../model/two/User";
import { useRequest } from "vue-request";
import { ref, computed, onMounted, watch, watchEffect } from "vue";
import axios from "../../api/request";

const ids = ref<number[]>([]);

const dto = ref({ page: 1, size: 10, name: "", email: "" });
const total = ref(0);
const visible = ref(false);

const {
  data,
  loading,
  run: runSearch,
} = useRequest<User[]>(
  () =>
    axios
      .get<ApiResponse>(
        `/api/userPage?page=${dto.value.page}&pageSize=${dto.value.size}&name=${dto.value.name}&email=${dto.value.email}`
      )
      .then((res) => {
        // userList.value = res.data.data;
        total.value = res.data.total;
        return res.data.data;
      }),
  {
    refreshDeps: [dto],
    manual: true,
  }
);

function onVisibleChange(v: boolean) {
  if (!v) {
    visible.value = false;
  } else {
    visible.value = ids.value.length > 0;
  }
}

function onDeleteIds() {
  if (ids.value.length > 0) {
    const idsStr: string = ids.value.join(",");
    doDeletes(idsStr);
  }
  runSearch();
}

function onSelectchange(keys: number[]) {
  ids.value = keys;
  console.log("selected Ids = %s", ids.value);
}

const { run: doDeletes } = useRequest<string>(
  (ids) =>
    axios.get<string>(`/api/deleteByIds?ids=${ids}`).then((res) => {
      return res.data;
    }),
  {
    manual: true,
  }
);

const { run: runDelete } = useRequest<number>(
  (id) =>
    axios.get<number>(`/api/deleteById?id=${id}`).then((res) => {
      return res.data;
    }),
  {
    manual: true,
  }
);

const userList = computed(() => data.value || []);

// 分页配置
const pagination = computed(() => ({
  current: dto.value.page,
  pageSize: dto.value.size,
  total: total.value,
  showTotal: (total: number) => `共 ${total} 条`,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ["5", "10", "20", "50"],
}));

// 切换分页时触发
function handleTableChange(paginationChange: any) {
  dto.value.page = paginationChange.current;
  dto.value.size = paginationChange.pageSize;
  pagination.value.current = paginationChange.current;
  pagination.value.pageSize = paginationChange.pageSize;
}

function handleSearch() {
  runSearch();
}

function doDelete(id: number) {
  console.log("delete id is %s", id);
  runDelete(id);
  runSearch();
}

watch(
  dto,
  () => {
    runSearch();
  },
  { deep: true }
);

onMounted(() => {
  runSearch();
});

const columns = ref([
  { title: "编号", dataIndex: "id" },
  { title: "姓名", dataIndex: "name" },
  {
    title: "邮箱",
    dataIndex: "email",
    customRender: ({ text }) => {
      return text ?? "-"; // 显示 null 时渲染为 "-"
    },
  },
  { title: "操作", dataIndex: "operator" },
]);

function rowkey(r: User) {
  return r.id;
}
</script>